# coding=utf-8
#

"""
服务端接口封装
"""

import json
import urllib
import requests


class QubicProxy(object):
    """ qubic 矿池的接口封装 """

    def __init__(self, access_token: str = ""):
        """ """
        self.host = "https://api.qubic.li/"
        self.key = access_token

    def request(self, method: str, uri: str, data: dict):
        """
        自己封装一个request方法，减少对于utils/http的引用

        Args:
            :param: uri(String): 请求的URI
            :param: method(String): 请求的HTTP Method
            :param: data(dict): 请求的参数集合

        Returns:
            resp
        """
        headers = {"Accept": "application/json", "Authorization": "Bearer %s" % self.key}

        url = urllib.parse.urljoin(self.host, uri)

        # GET时encode参数，POST时json化参数
        if method == "GET":
            data = urllib.parse.urlencode(data)
            url = url + '?' + data
        else:
            data = json.dumps(data)
            headers.update({"Content-Type": "application/json"})

        try:
            resp = requests.request(method, url, data=data, headers=headers)
            return resp.json()
        except Exception as msg:
            print(str(msg))
            # 网络请求失败或者json解析失败，则直接爆栈退出
            exit(1)

    def sync_pool_info(self):
        """ 同步矿池数据 """
        uri = "My/Pool"
        method = "GET"
        data = {}

        resp = self.request(method, uri, data)
        return resp

    def sync_agent_info(self, uid: str = ""):
        """  """
        uri = "My/Pool/%s/Performance" % uid
        method = "GET"
        data = {}

        resp = self.request(method, uri, data)
        return resp
